//获取应用实例
var app = getApp();
var FormCheckRule = {
    carNbrSufRule: /^[a-zA-Z0-9]{4}[a-zA-Z0-9\u4E00-\u9FA5]{1,2}$/,
    carCodeRule: /^[a-zA-Z0-9]{6}$/,
    nameRule: /^[\u4e00-\u9fa5]{2,12}$/,
    telRule: /^[1]{1}[0-9]{10}$/,
    carCodeNullMessage: "请输入车身架号后6位",
    carCodeErrorMessage: "请输入车身架号后6位",
    carNbrSufNullMessage: "请输入车牌号码",
    carNbrSufErrorMessage: "请输正确的车牌号码",
    cellNumNullMessage: "请输入收件人电话！",
    cellNumErrorMessage: "请输入正确的收件人电话！",
    contactNameNullMessage: "请输入收件人姓名！",
    contactNameErrorMessage: "请输入正确的收件人姓名！",
    areaNameNullMessage: "请选择所在地区！",
    streetNullMessage: "请输入详细地址！",
    num: 0
};


Page({
    data: {
        area: "请选择所在地区",
        areaStyle: "color: #B2B2B2;font-size:34rpx",
        errorFocusName: "",
        num: 0,
        items: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y'],
        carNumPrefix: "粤A",
        handleImage: "https://yzres.oss-cn-shenzhen.aliyuncs.com/apptest/images/bizType/img_nj_2@3x.png",
        conditions: "1、车辆注册日期在2013-10-13~2017-10-13之间的车辆。\n2、无未处理的交通违法。\n3、限定5座（包含5座）以下的蓝牌车。\n4、有效期内的交强险。\n",
        doc: "1、检验标志申请表（邮政速递人员上门揽收时提供）；\n2、行驶证正副本原件；\n3、交强险副本原件；\n4、车船税发票原件或免税证明原件（如交强险附带车船税购买的，只收交强险副本原件）\n",
        cardPicture: "",
        policyPicture: "",
        isNoticeShow: false,
        isAdvertShow: false,
        advertIconUrl: "",
        needInvoice: 0,
        agree: 0,
        isShowFootNav: true,
        isCanScroll: true,
        isShowSupplementaryData: false,//是否展示粤S
        address:{
            cityId:""
        }
    },
    onShareAppMessage: function () {   //分享功能
        return {
            title: '车辆年检',
            desc: '车辆年检',
            path: '/pages/handle/handle?scene='+app.globalData.channelId
        }
    },
    //底部切换页面方法
    toUrlTap: function (e) {
        var url = e.currentTarget.dataset.url;
        if (url != '/pages/handle/handle') {
            if (url == '') {
                //develop（开发版），trial（体验版），release（正式版）
                var res = {
                    appid: app.globalData.appid,
                    path: app.globalData.path,
                    envVersion: app.globalData.envVersion
                }
                app.crossToUrl(res)
            } else {
                app.redirectTo({ url: url+'?scene='+app.globalData.channelId });
            }
        }
    },
    onLoad: function (options) {
        // options 中的 scene 需要使用 decodeURIComponent 才能获取到生成二维码时传入的 scene
        app.globalData.channelId = decodeURIComponent(options.scene)=='undefined'?'':decodeURIComponent(options.scene);
        console.log("channelId",app.globalData.channelId);
        var pageObj = this;

        var advertOpt = {   //请求广告
            url: app.globalData.host + "/wx/an/ad.ajax",
            data: {},
            sucFn: function (result) {
                if (result.body.icon) {
                    pageObj.setData({
                        isAdvertShow: true,
                        advertIconUrl: result.body.icon
                    });
                }
            }
        };
        app.ajax(advertOpt);

        app.initAddress();
        var page = app.getStorageSync(app.globalData.cachePageKey);
        if (page != null && page != "") {
            this.setData({
                "carNumPrefix": page.carNumPrefix,
                "carNumberSuffix": page.carNumberSuffix,
                "carCode": page.carCode,
                "agree": page.agree
            });
            this.initCondition();

            if (page.carNumberSuffix != '' && page.carNumberSuffix != null) {
                if (FormCheckRule.carNbrSufRule.test(page.carNumberSuffix)) {
                    this.setData({ "carNumberSuffixIconType": "success" });
                } else if (page.carNumberSuffix.length > 0) {
                    this.setData({ "carNumberSuffixIconType": "error" });
                } else {
                    this.setData({ "carNumberSuffixIconType": "" });
                }
            }
            if (page.carCode != '' && page.carCode != null) {
                if (FormCheckRule.carCodeRule.test(page.carCode)) {
                    this.setData({ "carCodeIconType": "success" });
                } else if (page.carCodeRule.length > 0) {
                    this.setData({ "carCodeIconType": "error" });
                } else {
                    this.setData({ "carCodeIconType": "" });
                }
            }

            if (page.address != null) {
                this.setData({
                    "area": page.area,
                    "areaStyle": "",
                    "address.street": page.address.street,
                    "address.provinceId": page.address.provinceId,
                    "address.cityId": page.address.cityId,
                    "address.countyId": page.address.countyId,
                    "address.provinceName": page.address.provinceName,
                    "address.cityName": page.address.cityName,
                    "address.countyName": page.address.countyName,
                    "address.cellNum": page.address.cellNum,
                    "address.contactName": page.address.contactName
                });
                if (page.address.contactName != '' && page.address.contactName != null) {
                    if (FormCheckRule.nameRule.test(page.address.contactName)) {
                        this.setData({ "contactNameIconType": "success" });
                    } else if (page.address.contactName.length > 0) {
                        this.setData({ "contactNameIconType": "error" });
                    } else {
                        this.setData({ "contactNameIconType": "" });
                    }
                }

                if (page.address.cellNum != '' && page.address.cellNum != null) {
                    if (FormCheckRule.telRule.test(page.address.cellNum)) {
                        this.setData({ "cellNumIconType": "success" });
                    } else if (page.address.cellNum.length > 0) {
                        this.setData({ "cellNumIconType": "error" });
                    } else {
                        this.setData({ "cellNumIconType": "" });
                    }
                }
                if (page.area == '请选择所在地区') {
                    this.setData({ areaStyle: "color: #B2B2B2;font-size:34rpx" });
                } else {
                    this.setData({ areaStyle: "color:#1a1a1a;font-size:34rpx" });
                }
                if (page.certPlaceName == '') {
                    this.setData({ certPlaceStyle: "color: #B2B2B2;font-size:34rpx" });
                } else {
                    this.setData({ certPlaceStyle: "color:#1a1a1a;font-size:34rpx", certPlaceText: page.certPlaceName });
                }
            }
            this.setData({
                "cardName": page.cardName,
                "cardNum": page.cardNum,
                "telephone": page.telephone,
                "cardPicture": page.cardPicture,
                "policyPicture": page.policyPicture,
                "agree": page.agree
            });
            if (app.isYueS(page.carNumPrefix,page.address.cityId)) {//到付
                this.setData({ isShowSupplementaryData: true });
            }
        }

    },
    initCondition: function () {
        var pageObj = this;
        var carNumber = this.data.carNumPrefix;
        if (carNumber==null)return false;
        var opt = {
            url: app.globalData.host + "/wx/an/c.ajax",
            data: { carNumber: carNumber },
            sucFn: function (result) {
                pageObj.setData({
                    conditions: result.body.conditionArray.join("\n"),
                    doc: result.body.docArray.join("\n")
                });
            }
        };
        app.ajax(opt)
    },
    onHide: function () {
        app.setStorageSync(app.globalData.cachePageKey, this.data);
    },
    onShow: function () {
        var pageObj = this;
        if(app.globalData.isAuthSuccess){
            pageObj.getUserOrderList();
        }else {
            wx.login({//调用登录接口
                success: function (res) {
                    var opt = {//后台兑换openId
                        url: app.globalData.host + "/wx/an/eo.ajax",
                        data: {
                            'code': res.code
                        },
                        sucFn: function (result) {
                            if(result.body.authSuccess){
                                app.globalData.openId = result.body.openId;
                                app.globalData.isAuthSuccess = result.body.authSuccess;
                                pageObj.getUserOrderList();
                            }else{
                                app.toastAuthFailModal();
                            }
                        }
                    };
                    app.ajax(opt);
                }
            });
        }

        var page = app.getStorageSync(app.globalData.cachePageKey);
        this.setData({
            cardName: page.cardName,
            cardNum: page.cardNum,
            telephone: page.telephone,
            cardPicture: page.cardPicture,
            policyPicture: page.policyPicture,
            num: page.num
        });

        if (page.carNumPrefix == null) {
            this.setData({ carNumPrefix: "粤A" });
            this.setData({ isShowSupplementaryData: false });
            this.initCondition();
        }
        if (page.carNumberSuffix == null) {
            this.setData({ carNumberSuffix: null, carNumberSuffixIconType: "" });
        }
        if (page.carCode == null) {
            this.setData({ carCode: null, carCodeIconType: "" });
        }

    },
    getUserOrderList:function () {
        var that = this;
        var opt2 = {
            url: app.globalData.host+"/wx/an/list.ajax",
            data: {
                'accountId':app.globalData.openId,
                'bizFlag':app.globalData.bizDoingFlag,
                'orderType':app.globalData.orderType
            },
            sucFn:function (result) {
                var num = "";
                if(result.body.orderList.length!=0){
                    num = result.body.orderList.length;
                }
                that.setData({
                    "num": num
                });
            }
        };
        app.ajax(opt2);
    },
    //点击车牌前缀
    carNumPrefixTap: function (e) {
        this.setData({
            carNumPrefixShowView: true,
            isShowFootNav: false
        })
    },
    //确定车牌前缀
    confirmCarNumPrefixTap: function (e) {
        var isShowSupplementaryData = app.isYueS(e.target.dataset.name,this.data.address.cityId);
        this.setData({
            isShowSupplementaryData: isShowSupplementaryData,
            carNumPrefix: e.target.dataset.name,
            carNumPrefixShowView: false,
            isShowFootNav: true
        });
        this.initCondition();
    },
    //确定车牌前缀蒙层
    confirmCarNumPrefixViewTap: function (e) {
        this.setData({
            carNumPrefixShowView: false,
            isShowFootNav: true
        })
    },
    //取消
    cancelCarPrefixTap: function (e) {
        this.setData({
            carNumPrefixShowView: false,
            isShowFootNav: true
        })
    },
    mineTap: function (e) {
        app.setStorageSync(app.globalData.cachePageKey, this.data);
        var url = e.currentTarget.dataset.url;
        app.redirectTo({ url: url });
    },
    infoInput: function (e) {
        var id = e.currentTarget.id;
        var value = e.detail.value.replace(/(^\s*)|(\s*$)/g, "");
        if (id == "carNumberSuffix") {
            this.setData({ "carNumberSuffix": value });
            if (value == '') {
                this.setData({ "carNumberSuffixIconType": "success" });
            } else if (FormCheckRule.carNbrSufRule.test(value)) {
                this.setData({ "carNumberSuffixIconType": "success" });
            } else if (value.length > 0) {
                this.setData({ "carNumberSuffixIconType": "error" });
            } else {
                this.setData({ "carNumberSuffixIconType": "" });
            }

        } else if (id == "carCode") {
            this.setData({ "carCode": value });
            if (value == '') {
                this.setData({ "carCodeIconType": "success" });
            } else if (FormCheckRule.carCodeRule.test(value)) {
                this.setData({ "carCodeIconType": "success" });
            } else if (value.length > 0) {
                this.setData({ "carCodeIconType": "error" });
            } else {
                this.setData({ "carCodeIconType": "" });
            }

        } else if (id == "address.contactName") {
            this.setData({ "address.contactName": value });
            if (value == '') {
                this.setData({ "contactNameIconType": "success" });
            } else if (value.length > 0 && FormCheckRule.nameRule.test(value)) {
                this.setData({ "contactNameIconType": "success" });
            } else if (value.length > 0) {
                this.setData({ "contactNameIconType": "error" });
            } else {
                this.setData({ "contactNameIconType": "" });
            }
        } else if (id == "address.cellNum") {
            value = value.substr(0, 11);
            this.setData({ "address.cellNum": value });
            if (value == '') {
                this.setData({ "cellNumIconType": "success" });
            } else if (FormCheckRule.telRule.test(value)) {
                this.setData({ "cellNumIconType": "success" });
            } else if (value.length > 0) {
                this.setData({ "cellNumIconType": "error" });
            } else {
                this.setData({ "cellNumIconType": "" });
            }
        } else if (id == "address.street") {
            this.setData({ "address.street": value });
            if (value == '') {
                this.setData({ "streetIconType": "success" });
            } else if (value.length >= 5) {
                this.setData({ "streetIconType": "success" });
            } else if (value != '' && value != null && value.length < 5) {
                this.setData({ "streetIconType": "error" });
            } else {
                this.setData({ "streetIconType": "" });
            }
        }
    },
    carNumberSuffixBlur: function (e) {
        var value = e.detail.value;
        if (value != null && value != '') {
            this.setData({ carNumberSuffix: value.toUpperCase() });
        }
    },
    carCodeBlur: function (e) {
        var value = e.detail.value;
        if (value != null && value != '') {
            this.setData({ carCode: value.toUpperCase() });
        }
    },
    cardNumBlur: function (e) {
        var value = e.detail.value;
        if (value != null && value != '') {
            this.setData({ cardNum: value.toUpperCase() });
        }
    },
    formSubmit: function (e) {
        var pageObj = this;
        var formData = e.detail.value;
        var carNumberSuffix = formData.carNumberSuffix;
        var carNumPrefix = formData.carNumPrefix;
        var carNumber = formData.carNumber;
        var carCode = formData.carCode;

        var cellNum = formData['address.cellNum'];
        var contactName = formData['address.contactName'];
        var street = formData['address.street'];
        var provinceId = formData['address.provinceId'];
        var cityId = formData['address.cityId'];
        var isYueS = app.isYueS(carNumPrefix,cityId);
        var contactNameErrorScrollIntoViewName = isYueS ? 'policyPictureView' : 'carCodeView';

        var flag = app.check([
            {
                value: carNumberSuffix,
                errorFocusName: "carNumberSuffix",
                errorScrollIntoViewName: "handleView",
                fn: function (value) {
                    if ('' == value) {
                        app.errorToast(FormCheckRule.carNbrSufNullMessage);
                        return false;
                    } else if (FormCheckRule.carNbrSufRule.test(value)) {
                        return true;
                    } else {
                        app.errorToast(FormCheckRule.carNbrSufErrorMessage);
                        return false;
                    }
                }
            },
            {
                value: carCode,
                errorFocusName: "carCode",
                errorScrollIntoViewName: "handleView",
                fn: function (value) {
                    if ('' == value) {
                        app.errorToast(FormCheckRule.carCodeNullMessage);
                        return false;
                    } else if (FormCheckRule.carCodeRule.test(value)) {
                        return true;
                    } else {
                        app.errorToast(FormCheckRule.carCodeErrorMessage);
                        return false;
                    }
                }
            },
            //地址
            {
                value: contactName,
                errorFocusName: "contactName",
                errorScrollIntoViewName: contactNameErrorScrollIntoViewName,
                fn: function (value) {
                    if ('' == value) {
                        app.errorToast(FormCheckRule.contactNameNullMessage);
                        return false;
                    } else if (FormCheckRule.nameRule.test(value)) {
                        return true;
                    } else {
                        app.errorToast(FormCheckRule.contactNameErrorMessage);
                        return false;
                    }
                }
            },
            {
                value: cellNum,
                errorFocusName: "cellNum",
                errorScrollIntoViewName: "contactNameView",
                fn: function (value) {
                    if ('' == value) {
                        app.errorToast(FormCheckRule.cellNumErrorMessage);
                        return false;
                    } else if (FormCheckRule.telRule.test(value)) {
                        return true;
                    } else {
                        app.errorToast(FormCheckRule.cellNumErrorMessage);
                        return false;
                    }
                }
            },
            {
                value: provinceId,
                errorFocusName: "provinceId",
                errorScrollIntoViewName: "cellNumView",
                rule: app.globalData.Rule.required,
                fn: function (value) {
                    if (value != '') {
                        return true;
                    } else {
                        app.errorToast(FormCheckRule.areaNameNullMessage);
                        return false
                    }
                }
            },
            {
                value: street,
                errorFocusName: "street",
                errorScrollIntoViewName: "areaView",
                rule: app.globalData.Rule.required,
                fn: function (value) {
                    if (value.length >= 5) {
                        return true;
                    } else {
                        app.errorToast(FormCheckRule.streetNullMessage);
                        return false
                    }
                }
            }
        ]);
        if (!flag) {
            return false;
        }
        if (!app.globalData.isAuthSuccess) {
            app.toastAuthFailModal();
            return false;
        }
        var param = formData;
        param['address.fullAddr'] = formData['address.provinceName'] + formData['address.cityName'] + formData['address.countyName'] + street;
        var opt = {
            url: app.globalData.host + "/wx/an/handling.ajax",
            data: param,
            sucFn: function (result) {
                param['serviceFee'] = result.body.serviceFee;
                param['doc'] = pageObj.data.doc;
                param['serviceFeeDesc'] = result.body.serviceFeeDesc;
                param['totalChargeFee'] = result.body.totalChargeFee;
                param['totalFee'] = result.body.totalFee;
                app.setStorageSync(app.globalData.cacheOrderResKey, param);
                if (result.body.hasViolation == 0) {//0/没有 1/有 2/未知
                    pageObj.jumpTo(formData);;
                } else if (result.body.hasViolation == 1) {// 1 有违章
                    var opt = {
                        title: "温馨提示",
                        content: "系统检测到您的车" + param.carNumber + "有未办理违章，请处理完违章再办理年检",
                        cancelText: "确定",
                        confirmText: "去办年检",
                        success: function () {
                            pageObj.jumpTo(formData);
                        },
                        cancel: function () {
                            console.log("确定");
                        }
                    };
                    app.showModal(opt);
                } else if (result.body.hasViolation == 2) {//2 未知
                    var opt = {
                        title: "温馨提示",
                        content: "系统检测不到您的车" + param.carNumber + "的违章情况，请确认您的车无违章后再办理年检",
                        cancelText: "确定",
                        confirmText: "去办年检",
                        success: function () {
                            pageObj.jumpTo(formData);
                        },
                        cancel: function () {
                            console.log("确定");
                        }
                    };
                    app.showModal(opt);
                } else if (result.body.hasViolation == 3) {//3 年检未到期
                    var opt = {
                        title: "暂不需要年检",
                        content: "系统检测到" + param.carNumber + "检验有效期至：" + result.body.endTime,
                        cancelText: "确定",
                        confirmText: "去办年检",
                        success: function () {
                            pageObj.jumpTo(formData);
                        },
                        cancel: function () {
                            console.log("确定");
                        }
                    };
                    app.showModal(opt);
                }
            }
        };
        app.ajax(opt);
    },
    // 点击办理按钮跳转
    jumpTo:function(formData){
        var carNumPrefix = formData.carNumPrefix;
        var provinceId = formData['address.provinceId'];
        var cityId = formData['address.cityId']; 
        // 如果车牌是粤s且地址为东莞，跳到补充资料页面
        if(app.isYueS(carNumPrefix.toUpperCase(),cityId)){
            app.navigateTo({ url: './addInfo/addInfo' });
        }else{
            app.navigateTo({ url: '../payment/payment' });
        }
    },
    agreeTap: function (e) {
        this.setData({
            isNoticeShow: true,
            isShowFootNav: false
        });
    },
    uploadTap: function (e) {
        var type = e.currentTarget.dataset.type;
        var value = e.currentTarget.dataset.value;
        app.navigateTo({
            url: '../handle/upload/upload?type=' + type + '&uploadImgSrc=' + value
        });
    },
    checkTap: function (e) {
        var agree = e.target.dataset.agree;
        if (agree == 0) {
            agree = 1;
        } else {
            agree = 0;
        }
        this.setData({ agree: agree });
    },
    noticeKnowTap: function (e) {
        this.setData({
            isNoticeShow: false,
            isShowFootNav: true
        });
    },
    areaTap: function (e) {
        this.setData({
            isAddressShow: true,
            isShowFootNav: false
        });
    },
    addressShowTap: function (e) {
        this.setData({
            isAddressShow: false,
            isShowFootNav: true
        });
    },
    bindAddressChange: function (e) {
        app.bindAddressChange(e);
    },
    confirmAddressTap: function (e) {
        var current_value = this.data.value;
        var provinceName = this.data.proviceData[current_value[0]].name;
        var cityName = this.data.cityData[current_value[1]].name;
        var countyName = "";
        if (this.data.districtData[current_value[2]].name != null) {
            countyName = this.data.districtData[current_value[2]].name;
        }
        var isShowSupplementaryData = app.isYueS(this.data.carNumPrefix,this.data.cityData[current_value[1]].id);
        this.setData({
            isShowSupplementaryData: isShowSupplementaryData,
            isShowFootNav: true,
            isAddressShow: false,
            areaStyle: "color:#1a1a1a;font-size:34rpx",
            area: provinceName + cityName + countyName,
            "address.provinceId": this.data.proviceData[current_value[0]].id,
            "address.cityId": this.data.cityData[current_value[1]].id,
            "address.countyId": this.data.districtData[current_value[2]].id,
            "address.provinceName": provinceName,
            "address.cityName": cityName,
            "address.countyName": countyName
        });
    },
    cancelAddressTap: function (e) {
        this.setData({
            isShowFootNav: true,
            isAddressShow: false
        });
    }
});
